﻿using System;
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace Jumbot.DataOper
{
    /// <summary>
    /// 提供对Xls文档的操作接口。
    /// </summary>
    public class XlsControl
    {
        private string _strXlsFile;
        private OleDbConnection _con;


        /// <summary>
        /// TODO: 在这里加入建构函式的程序代码 
        /// </summary>
        /// <param name="XlsFile"></param>
        public XlsControl(string _XlsFile)
        {
            try
            {
                OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + _XlsFile);
                _con = con;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            _strXlsFile = _XlsFile;
        }
        /// <summary>
        /// 返回一个Sheet的数据到DataTable
        /// </summary>
        /// <param name="_SheetName">表名</param>
        /// <returns></returns>
        public DataTable GetData(string _SheetName)
        {
            DataSet _ds = new DataSet();
            try
            {
                if (_con.State != ConnectionState.Open)
                {
                    _con.Open();
                }
                else
                {
                    return null;
                }
                OleDbCommand _cmd = new OleDbCommand(@"select * from [" + _SheetName + "$]", _con);
                OleDbDataAdapter _da = new OleDbDataAdapter();
                _da.SelectCommand = _cmd;
                _da.Fill(_ds);
                _con.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return _ds.Tables[0];
        }
    }
}
